from rest_framework.serializers import ModelSerializer
from goods.models import Goods, Combo, Middle, Message, Message2
from rest_framework import serializers


class MessageSer(ModelSerializer):
    username = serializers.SerializerMethodField()

    def get_username(self, obj):
        return obj.user.username

    class Meta:
        model = Message
        fields = '__all__'


class GoodsSer(ModelSerializer):
    class Meta:
        model = Goods
        fields = '__all__'


class ComboSer(serializers.ModelSerializer):
    goods_names = serializers.SerializerMethodField()

    class Meta:
        model = Combo
        fields = '__all__'

    def get_goods_names(self, obj):
        # 通过中间表查询该套餐下的所有商品
        goods_qs = Goods.objects.filter(middle__combo=obj)
        # 使用 GoodsSer 序列化商品
        serializer = GoodsSer(goods_qs, many=True, context=self.context)
        return serializer.data


class MiddleSer(ModelSerializer):
    good = serializers.SerializerMethodField(read_only=True)

    def get_good(self, obj):
        return obj.goods.name

    class Meta:
        model = Middle
        fields = '__all__'


class Message2Ser(ModelSerializer):
    username = serializers.SerializerMethodField()

    def get_username(self, obj):
        return obj.user.username

    class Meta:
        model = Message2
        fields = '__all__'
